package com.gitee.chenyaohua.conn;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionPoolFactory  extends BasePooledObjectFactory<Connection> {

    /**
     * 驱动类名
     */
    private String driverClass;
    /**
     * 用户名
     */
    private String username;
    /**
     * 数据库连接
     */
    private String jdbcUrl;
    /**
     * 数据库密码
     */
    private String password;

    public ConnectionPoolFactory(String driverClass, String username, String jdbcUrl, String password) {
        this.driverClass = driverClass;
        this.username = username;
        this.jdbcUrl = jdbcUrl;
        this.password = password;
    }

    /**
     * 创建实例
     * @return
     * @throws Exception
     */
    @Override
    public Connection create() throws Exception {
        Class.forName(driverClass);
        return DriverManager.getConnection(jdbcUrl, username, password);
    }

    @Override
    public PooledObject<Connection> wrap(Connection obj) {
        return new DefaultPooledObject<>(obj);
    }
}
